 const fs = require('fs'); //引入fs读取文件内容
 const path = require('path'); //引入文件夹路径
 const Sequelize =  require('Sequelize');  //引入Sequelize
const config = require('../config/default'); //引入配置文件
const {db} = config;   //解构出配置文件中的db项
const basename = path.basename(__filename);  //获取文件名称

const {database, username, password} = db; 

const squelize = new Sequelize(database, username, password, db.options); //新建squelize实例

fs.readdirSync(__dirname).filter(file => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) ==='.js'))
.forEach((file) => {
    const model = squelize.import(path.join(__dirname, file));
    db[model.name] = model;
});

Object.keys(db).forEach((modelName) => {
    if(db[modelName].associate){
        db[modelName].associate(db);
    }
});

db.squelize = squelize;
db.Sequelize = Sequelize;

module.exports = db;

